<template>
  <div class="delegationUserInfo">
    <!-- 顶部插槽 -->
    <el-row>
      <el-col :span="19" :offset="5">
        <slot name="top" />
      </el-col>
    </el-row>

    <!-- 团体信息 -->
    <el-form ref="refDelegationInfo" :model="insideTeamData" :rules="teamUserInfoVO_Rules" label-width="120px">
      <el-row>
        <!-- 团体头像图片 -->
        <el-col :span="5">
          <div class="delegationUserInfo_img_wrap">
            <el-form-item label-width="20px" align="center" prop="imagePath">
              <el-input v-show="false" v-model.trim="insideTeamData.imagePath" />
              <el-dialog class="gl_dialog_TitleLine" width="880px" title="上传图片" :append-to-body="true" :visible.sync="photoCropperVisible" :close-on-click-modal="false" :close-on-press-escape="false">
                <photo-cropper ref="photoCropper" :action="action" :option="photoCropperOption" height="375px" @photoCropperSave="photoCropperSave" />
              </el-dialog>
              <div class="upload_game_img" :class="isCheckMode('imagePath') ? '' : 'no_pointer'" @click="openPhotoCropper">
                <img v-if="insideTeamData.imagePath" class="show_img" :src="getStaticPhotoUrl(insideTeamData.imagePath)">
                <i v-else class="el-icon-plus" />
              </div>
            </el-form-item>
          </div>
          <div v-if="isCheckMode('imagePath')">
            <p class="tip_info_style">请上传彩色照片</p>
            <p class="tip_info_style">文件格式：jpg、jpeg、png</p>
            <p class="tip_info_style">照片大小不能超过3M</p>
          </div>
        </el-col>
        <!-- 团体信息 -->
        <el-col :span="19">
          <el-row v-if="isShowCode">
            <el-col :span="8">
              <el-form-item label="绑定ID">
                <span>{{ insideTeamData.code }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="代表队名称" prop="name">
                <el-input v-if="isCheckMode('name')" v-model.trim="insideTeamData.name" placeholder="请输入代表队名称" type="text" size="mini" />
                <span v-else>{{ insideTeamData.name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代表队简称" prop="shortName">
                <el-input v-if="isCheckMode('shortName')" v-model.trim="insideTeamData.shortName" placeholder="请输入代表队简称" type="text" size="mini" />
                <span v-else>{{ insideTeamData.shortName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代表队类型" prop="delegationTypeCode">
                <el-select v-if="isCheckMode('delegationTypeCode')" v-model="insideTeamData.delegationTypeCode" placeholder="请选择代表队类型" size="mini" style="width: 100%">
                  <el-option v-for="item in dict.delegationType" :key="item.code" :label="item.value" :value="item.code" />
                </el-select>
                <span v-else>{{ findDictDataByCode('delegationType', insideUserData.delegationTypeCode).value }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="16">
              <el-form-item label="所在地区" prop="provinceCode">
                <el-cascader v-if="isCheckMode('addressData')" v-model="insideTeamData.addressData" size="mini" :options="cache.district" :props="{ value: 'code', label: 'name' }" placeholder="请选择省市区" style="width: 100%;" @change="onChangeAddressData" />
                <span v-else class="form_content" :title="addressDataForCheck">{{ addressDataForCheck }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="16" class="reset_address_error">
              <el-form-item label="详细地址" prop="address">
                <el-input v-if="isCheckMode('address')" v-model.trim="insideTeamData.address" placeholder="请输入详细地址" type="textarea" :autosize="{ minRows: 2, maxRows: 3}" size="mini" />
                <span v-else>{{ insideTeamData.address }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input v-if="isCheckMode('contactPerson')" v-model.trim="insideTeamData.contactPerson" placeholder="请输入联系人姓名" type="text" size="mini" />
                <span v-else>{{ insideTeamData.contactPerson }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系方式" prop="phoneNumber">
                <el-input v-if="isCheckMode('phoneNumber')" v-model.trim="insideTeamData.phoneNumber" placeholder="请输入联系人手机号" type="text" size="mini" />
                <span v-else>{{ insideTeamData.phoneNumber }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="中跆协会员号">
                <el-input v-if="isCheckMode('ctkCode')" v-model.trim="insideTeamData.ctkCode" placeholder="请输入中跆协会员号" type="text" size="mini" />
                <span v-else>{{ insideTeamData.ctkCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="省跆协会员号">
                <el-input v-if="isCheckMode('ptkCode')" v-model.trim="insideTeamData.ptkCode" placeholder="请输入省跆协会员号" type="text" size="mini" />
                <span v-else>{{ insideTeamData.ptkCode }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 实名认证照片正反面 -->
          <el-row v-if="isShowIdCardImage">
            <el-col :span="24">
              <div class="gl_clear">
                <div class="img_box">
                  <el-form-item label="实名认证" style="width:370px" prop="licenseImage">
                    <upload-file
                      v-if="isCheckMode('licenseImage')"
                      class="imgt_upload"
                      :file-name="'机构营业执照'"
                      :action="action"
                      :show-file-list="false"
                      :limit="1"
                      file-type="file"
                      format-file=".jpg,.jpeg,.png"
                      :default-file-url="getStaticPhotoUrl(insideTeamData.licenseImage)"
                      @uploadSuccess="saveUploadImg($event, 'licenseImage')"
                    />
                    <div v-else class="imgt_upload no_pointer">
                      <img v-if="insideTeamData.licenseImage" :src="getStaticPhotoUrl(insideTeamData.licenseImage)">
                    </div>
                  </el-form-item>
                </div>
                <!-- 只在证件类型是身份证时才显示证件照反面 -->
                <div class="img_box">
                  <el-form-item label="" label-width="20px" style="width:260px" prop="idCardImage">
                    <upload-file
                      v-if="isCheckMode('idCardImage')"
                      class="imgt_upload"
                      :file-name="'机构法人证件照正面'"
                      :action="action"
                      :show-file-list="false"
                      :limit="1"
                      file-type="file"
                      format-file=".jpg,.jpeg,.png"
                      :default-file-url="getStaticPhotoUrl(insideTeamData.idCardImage)"
                      @uploadSuccess="saveUploadImg($event, 'idCardImage')"
                    />
                    <div v-else class="imgt_upload no_pointer">
                      <img v-if="insideTeamData.idCardImage" :src="getStaticPhotoUrl(insideTeamData.idCardImage)">
                    </div>
                  </el-form-item>
                </div>
                <div class="img_box">
                  <el-form-item label="" label-width="20px" style="width:260px" prop="idCardBackImage">
                    <upload-file
                      v-if="isCheckMode('idCardBackImage')"
                      class="imgt_upload"
                      :file-name="'机构法人证件照正面反面'"
                      :action="action"
                      :show-file-list="false"
                      :limit="1"
                      file-type="file"
                      format-file=".jpg,.jpeg,.png"
                      :default-file-url="getStaticPhotoUrl(insideTeamData.idCardBackImage)"
                      @uploadSuccess="saveUploadImg($event, 'idCardBackImage')"
                    />
                    <div v-else class="imgt_upload no_pointer">
                      <img v-if="insideTeamData.idCardBackImage" :src="getStaticPhotoUrl(insideTeamData.idCardBackImage)">
                    </div>
                  </el-form-item>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>

    <!-- 底部插槽 -->
    <el-row>
      <el-col :span="19" :offset="5">
        <slot name="bottom" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { CopyData } from '@/lib';

import {
  SiSTKWEventsManagementCreateDelegationInput
} from '@/lib/form/game/swaggerForm';

import { TeamUserInfoVO_Rules } from '@/lib/validate/myCenter';

import uploadFile from './uploadFileDialog';
import photoCropper from '@/components/PhotoCropper';

export default {
  name: 'TeamInfo',
  components: {
    photoCropper,
    uploadFile
  },
  props: {
    // 传入的团体信息数据
    teamData: {
      type: Object,
      default() {
        return {};
      }
    },
    isShowCode: {
      type: Boolean,
      default: false
    },
    // 是否显示证件照正反面图片上传
    isShowIdCardImage: {
      type: Boolean,
      default: true
    },
    // 是否为查看模式，查看模式将把预设好的字段变为不可编辑状态
    isCheck: {
      type: Boolean,
      default: false
    },
    // 默认的查看模式以原型为基准：包括 name, nationality, nation, idCardTypeCode, idCardNumber, genderCode, birthDate, addressData
    isDefaultCheck: {
      type: Boolean,
      default: false
    },
    // 查看模式字段集合，由调用组件传值决定，示例：['name']
    checkList: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data () {
    return {
      insideTeamData: new SiSTKWEventsManagementCreateDelegationInput(), // 组件内使用的用户数据
      teamUserInfoVO_Rules: new TeamUserInfoVO_Rules(), // 数据验证规则
      photoCropperVisible: false, // 上传图片窗口的显示与隐藏
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      photoCropperOption: {
        img: ''
      }
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    }),
    // 显示为只可查看字段的map
    checkListMap () {
      if (this.isDefaultCheck) {
        return {
          name: true,
          shortName: true,
          delegationTypeCode: true,
          addressData: true
        };
      } else {
        const _map = {};
        this.checkList.forEach(item => {
          _map[item] = true;
        });
        return _map;
      }
    },
    // 根据所在地区Code找到对应name
    addressDataForCheck () {
      const _provinceCode = this.insideTeamData.provinceCode;
      const _cityCode = this.insideTeamData.cityCode;
      const _countyCode = this.insideTeamData.countyCode;
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    }
  },
  watch: {
    teamData: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) {
          this.init(val);
        }
      }
    }
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    // 初始化数据
    init (data) {
      CopyData(data, this.insideTeamData);
      this.insideTeamData.addressData = [data.provinceCode, data.cityCode, data.countyCode];
      // this.getDict();
      // this.getDictByType();
    },
    // 外部获取组件数据的方法
    getInsideTeamData () {
      return new Promise((reslove, reject) => {
        this.$refs.refDelegationInfo.validate((valid) => {
          if (valid) {
            reslove(this.insideTeamData);
          } else {
            reject(null);
          }
        });
      });
    },
    // 清空数据及验证
    clearInsideTeamData () {
      this.$refs.refDelegationInfo.resetFields();
    },
    // 字段是否只可查看处理函数
    isCheckMode (key) {
      // 如果 isCheck 存在则以 isCheck 为准
      if (this.isCheck) {
        return !this.isCheck;
      } else {
        return !(key in this.checkListMap);
      }
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    // 更改所在地区，将信息传入需要的Code中
    onChangeAddressData () {
      const _addressData = this.insideTeamData.addressData;
      this.insideTeamData.provinceCode = _addressData ? _addressData[0] || '' : '';
      this.insideTeamData.cityCode = _addressData ? _addressData[1] || '' : '';
      this.insideTeamData.countyCode = _addressData ? _addressData[2] || '' : '';
    },
    // 点击打开照片裁剪窗口
    openPhotoCropper () {
      const _canEdit = this.isCheckMode('imagePath');
      if (_canEdit) {
        if (this.insideTeamData['imagePath']) {
          this.$set(this.photoCropperOption, 'img', this.getStaticPhotoUrl(this.insideTeamData['imagePath']));
        }
        this.photoCropperVisible = true;
      }
    },
    // 点击保存照片裁剪窗口
    photoCropperSave (uploadImg) {
      this.$refs.photoCropper.upload().then(res => {
        this.$set(this.insideTeamData, 'imagePath', res.tempUrl);
        this.photoCropperVisible = false;
      });
    },
    // 获取静态文件
    getStaticPhotoUrl (relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 上传图片成功处理回调
    saveUploadImg (fileUrl, key) {
      this.$set(this.insideTeamData, key, fileUrl.tempUrl);
    }
  }
};
</script>

<style>
  .delegationUserInfo_img_wrap .el-form-item__error {
    padding-left: 10px;
  }
  .delegationUserInfo .el-form-item__error{
    padding-top: 0;
    margin-top: -4px;
  }
  .delegationUserInfo .reset_address_error .el-form-item__error {
    margin-top: 2px;
  }
</style>

<style lang="scss" scoped>
  .tip_info_style {
    padding: 0 10px 0 30px;
    font-size: 14px;
    color: #C0C4CC;
  }
  .personal{
    color: #333;
    box-shadow: 0px 2px 10px rgba(0, 0, 0, 0.09);
  }
  .box{
    width: 100px;
    height: 100px;
    display: inline-block;
    position: relative;
    border-radius: 10px;
    overflow: hidden;
  }
  .el-form>>>.el-form-item {
    margin-bottom: 10px;
  }
  .el-cascader {
    width: 100%;
  }
  .label {
    text-align: right;
    font-weight: 700;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #606266;
    line-height: 40px;
    padding: 0 12px 0 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
  }
  .content {
    line-height: 40px;
    position: relative;
    font-size: 14px;
  }
  .img_box {
    float: left;
  }
  .imgt_upload {
    width: 240px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
  .imgt_upload.no_pointer {
    cursor: default;
  }
  .imgt_upload:hover {
    border-color: #409EFF;
  }
  .img_content {
    width: 240px;
    height: 90px;
    margin-top: 30px;
    text-align: center;
  }
  .imgt-icon {
    font-size: 28px;
    color: #8c939d;
  }
  .imgt {
    width: 240px;
    height: 150px;
    display: block;
  }
  .boxItem_left{
    padding-bottom: 10px;
    width: 70%;
    float: left;
  }
  .boxItem_right{
    width: 30%;
    float: left;
  }
  .no_tag {
    padding-left: 15px;
    color: #C0C4CC;
    font-size: 12px;
  }
  .form_content {
    box-sizing: border-box;
    display: inline-block;
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
    vertical-align: top;
    text-overflow: ellipsis;
  }
  .upload_game_img.no_pointer {
    cursor: default;
  }
  .upload_game_img {
    width: 200px;
    height: 200px;
    line-height: 200px;
    text-align: center;
    font-size: 20px;
    border: 1px dotted #DCDFE6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    margin: 10px 0;
  }
  .upload_game_img .show_img {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
  }
</style>
